<?php
/**
 * 发送群消息
 */
namespace App\Service;

use App\Common;
use App\Model\Callback;
use App\Model\GroupMsg;
use App\Model\GroupUser;
use App\Model\UserBind;
use App\ServiceInterface;
use Hyperf\DbConnection\Db;
use function GuzzleHttp\json_encode;

class SendgroupService implements ServiceInterface
{
    private $_srever;

    private $_fd;

    private $_data;

    /**
     * BindService constructor.
     * @param null $server
     * @param int $fd
     * @param array $data
     */
    public function __construct($server=null,int $fd=0,array $data=[])
    {
        $this->_srever = $server;
        $this->_fd     = $fd;
        $this->_data   = $data;
    }

    /**
     * 参数校验
     * @return string
     */
    public function check():string
    {
        if (!isset($this->_data['g_id']) || intval($this->_data['g_id']) <= 0)
        {
            return 'g_id is null';
        }
        if (!isset($this->_data['account']) || empty($this->_data['account']))
        {
            return 'account is null';
        }

        if (!isset($this->_data['content']) || empty($this->_data['content']))
        {
            return 'content is null';
        }

        return '';
    }

    /**
     * 具体逻辑
     * @return array
     */
    public function init():array
    {
        try {
            $check_msg = $this->check();
            if ($check_msg)
                throw new \Exception($check_msg);

            // 1、通过群id获取所有用户
            $user = GroupUser::getGroupUserAll($this->_data['appid'],$this->_data['g_id']);
            if (!$user || !is_array($user))
                throw new \Exception('群组不不在');

            $time = time();

            $a_user = UserBind::where(
                [
                    'appid'  =>$this->_data['appid'],
                    'account'=>$this->_data['account']
                ])
                ->first('avatar');

            $data = json_encode(
                [
                    'tag'     => 'group',
                    'action'  => 'receiveGroupMsg',
                    'g_id'    => $this->_data['g_id'],
                    'account' => $this->_data['account'],
                    'avatar'  => $a_user->avatar ?? '',
                    'content' => $this->_data['content'],
                    'g_name'  => '',
                    'g_avatar' => '',
                    'time'    => $time
                ],JSON_UNESCAPED_UNICODE);
            foreach ($user as $val)
            {
                if (intval($val->fd) > 0 && $val->account != $this->_data['account'])
                {
                    $this->_srever->push($val->fd, $data);
                }
            }

            // 写库
            $msg = [
                'appid'   => $this->_data['appid'],
                'account' => $this->_data['account'],
                'g_id'    => $this->_data['g_id'],
                'content' => serialize($this->_data['content']),
                'created_at' => time(),
            ];
            $id = GroupMsg::insertGetId($msg);

            // 更新group_user 的 last_ack_msgid 最后已读的消息的id
            GroupUser::updateRead($this->_data['appid'],$this->_data['account'],$this->_data['g_id'],$id);


            $this->callback();

            return [0, 'success', ['msgid'=>time() . $id]];
        }catch (\Exception $e){
            return [-1,$e->getMessage()];
        }
    }

    /**
     * 发送回调
     */
    private function callback()
    {
        $appid = $this->_data['appid'];
        $callback = Callback::where(['appid'=>$appid])->first(['sendgroup']);
        if (!$callback) return;

        if ($callback['sendgroup']){
            $data = [
                'code' => 0,
                'msg'  => 'ok',
                'info' => [
                    'account' => $this->_data['account'],
                    'g_id'    => $this->_data['g_id'],
                    'content' => $this->_data['content'],
                ]
            ];
            Common::http_request($callback['sendmsg'], $data);
        }
    }

}